package ui.fragment.minefragment;

import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;

import org.angmarch.views.NiceSpinner;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.StudyReportAdapter;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.StudyReportDetailBean;
import student.andlei.com.student.R;
import utils.BarChartManager;
import utils.GsonUtils;
import utils.StringUtils;
import utils.TimerUtil;
import view.FullyLinearLayoutManager;

/**
 * 学习报告
 */
public class StudyReportFragment extends BaseNetFragment{
    private TextView tv_monthly,tv_weekly,tv_content;
    private NiceSpinner niceSpinner,niceSpinner_week;
    private BarChart barChart;
    private TextView barchart_text_kong;
    private RecyclerView recyclerView;
    private StudyReportAdapter adapter;
    private StudyReportDetailBean reportDetailBean;
    private BarChartManager barChartManager1;
    private List<StudyReportDetailBean.Rank> lists = new ArrayList<>();
    private int type = 1;//1:月 2:周
    private int month = 1;
    public static Fragment getInstance() {
        return new StudyReportFragment();
    }
    @Override
    public void success(String action, BaseBean baseBean) {
        if(baseBean.code==200){
            reportDetailBean = (StudyReportDetailBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,StudyReportDetailBean.class);
           //----------------学习报告统计------------------
           String str =  "亲爱的"+reportDetailBean.student_name+"同学：<br><br>"+
                    "在此期间内，您应交作业<font color = \"#FF1B1B\">"+(StringUtils.isNull(reportDetailBean.statistics.task_total)?"0": StringUtils.str2Int(reportDetailBean.statistics.task_total) )+"份</font>,"+
                    "正常提交作业<font color = \"#FF1B1B\">"+ (StringUtils.isNull(reportDetailBean.statistics.normal_total)?"0":StringUtils.str2Int(reportDetailBean.statistics.normal_total) )+"份</font>，"+
                    "占比<font color = \"#FF1B1B\">"+(StringUtils.isNull(reportDetailBean.statistics.normal_total_rate)?"0":StringUtils.str2Double(reportDetailBean.statistics.normal_total_rate))+"%</font>，"+
                    "延交作业<font color = \"#FF1B1B\">"+(StringUtils.isNull(reportDetailBean.statistics.delay_total)?"0": StringUtils.str2Int(reportDetailBean.statistics.delay_total))+"份</font>，"+
                    "占比<font color = \"#FF1B1B\">"+(StringUtils.isNull(reportDetailBean.statistics.delay_total_rate)?"0": StringUtils.str2Double(reportDetailBean.statistics.delay_total_rate))+"%</font>，"+
                    "未交作业<font color = \"#FF1B1B\">"+(StringUtils.isNull(reportDetailBean.statistics.no_submit_total)?"0": StringUtils.str2Int(reportDetailBean.statistics.no_submit_total))+"份</font>，"+
                    "占比<font color = \"#FF1B1B\">"+(StringUtils.isNull(reportDetailBean.statistics.no_submit_total_rate)?"0": StringUtils.str2Double(reportDetailBean.statistics.no_submit_total_rate))+"%</font>；<br><br>"+
                    "共做题<font color = \"#FF1B1B\">"+(StringUtils.isNull(reportDetailBean.statistics.total_question)?"0": StringUtils.str2Int(reportDetailBean.statistics.total_question))+"道</font>，"+
                    "错题<font color = \"#FF1B1B\">"+(StringUtils.isNull(reportDetailBean.statistics.error_question)?"0": StringUtils.str2Int(reportDetailBean.statistics.error_question))+"道</font>，"+
                    "得分率<font color = \"#FF1B1B\">"+(StringUtils.isNull(reportDetailBean.statistics.error_rate)?"0": StringUtils.str2Double(reportDetailBean.statistics.error_rate))+"%</font>。";
            tv_content.setText(Html.fromHtml(str));
            //------------------图表显示------------
            ArrayList<String> xValues = new ArrayList<>();
            List<Float> yValue1 = new ArrayList<>();
            List<Float> yValue2 = new ArrayList<>();
            if(reportDetailBean.subject.size()>0){
                for(StudyReportDetailBean.Subject subject : reportDetailBean.subject){
                    xValues.add(subject.subject_name);
                    if(!StringUtils.isNull(subject.avg_score)){
                        yValue1.add(Float.valueOf(subject.avg_score));
                    }else {
                        yValue1.add(Float.valueOf(0));
                    }
                    if(!StringUtils.isNull(subject.last_avg_score)){
                        yValue2.add(Float.valueOf(0));
                    }else {
                        yValue2.add(Float.valueOf(0));
                    }

                }
                if((xValues.size()>0&&yValue1.size()>0)&&yValue2.size()>0){
                    barChartManager1.setTwoBarChart(barChart,xValues,yValue1,yValue2,"上月","本月");
                    barChart.setVisibility(View.VISIBLE);
                    barchart_text_kong.setVisibility(View.GONE);
                }
            }else {
                barChart.setVisibility(View.GONE);
                barchart_text_kong.setVisibility(View.VISIBLE);
            }

            //------------------班级排名------------
            lists = reportDetailBean.rank;
            adapter.setNewData(lists);
        }else {
            toast(baseBean.msg);
        }
    }

    @Override
    public void error(String action, Throwable e) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_studyreport;
    }

    @Override
    protected void findViews() {
        tv_monthly= getView(R.id.tv_monthly);
        tv_weekly = getView(R.id.tv_weekly);
        tv_content = getView(R.id.tv_content);
        niceSpinner = getView(R.id.Spann_select);
        niceSpinner_week = getView(R.id.Spann_select_week);
        barChart = getView(R.id.barchart_);
        barchart_text_kong = getView(R.id.barchart_text_kong);
        recyclerView = getView(R.id.rcly_);
    }
    //private List<String> weekList = new ArrayList<>();
    private List<String> initWeekData() {
        List<String> weekList = new ArrayList<>();
        int nowYear = Calendar.getInstance().get(Calendar.YEAR);
        int nowWeek = Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
        Calendar gregorianCalendar = new GregorianCalendar(nowYear, 0, 1);
        int i = 0;
        while (gregorianCalendar.get(Calendar.YEAR) < nowYear + 1 && gregorianCalendar.get(Calendar.WEEK_OF_YEAR) < nowWeek + 1) {
            gregorianCalendar.set(Calendar.DAY_OF_WEEK, i++);
            gregorianCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            String tempDate = "";
            if (gregorianCalendar.get(Calendar.YEAR) <= nowYear) {
                tempDate = getDateString(gregorianCalendar);
            }
//            gregorianCalendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
            gregorianCalendar.set(Calendar.DATE, gregorianCalendar.get(Calendar.DATE) + 6);
            if (gregorianCalendar.get(Calendar.YEAR) <= nowYear) {
                tempDate = tempDate + "到" + getDateString(gregorianCalendar);
                weekList.add(tempDate);
            }
        }
        Collections.reverse(weekList);
        return weekList;
    }
    private String getDateString(Calendar gregorianCalendar) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(gregorianCalendar.getTime());
    }


    @Override
    protected void formatViews() {
        tv_monthly.setOnClickListener(this);
        tv_weekly.setOnClickListener(this);
        //创建布局管理
        FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(this.context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new StudyReportAdapter(R.layout.item_tab_mark,lists);
        recyclerView.setAdapter(adapter);
        barChartManager1 = new BarChartManager(barChart);
        barChartManager1.setYAxis(100,0,10);
        barChartManager1.setDescription("成绩比对表");
        //barChartManager1.setHightLimitLine(100,"满分线",Color.BLUE);
        //设置x轴的数据
//        ArrayList<String> xValues = new ArrayList<>();
//        xValues.add("语文");
//        xValues.add("数学");
//        xValues.add("英语");
//        xValues.add("信息技术");
//        xValues.add("物理");
//        xValues.add("化学");
//        xValues.add("生物");
//        xValues.add("内部课程");
//        //设置y轴的数据()
//        List<List<Float>> yValues = new ArrayList<>();
//        List<Float> yValue1 = new ArrayList<>();
//        List<Float> yValue2 = new ArrayList<>();
//        for (int j = 0; j <= 10; j++) {
//                yValue1.add((float) (Math.random() * 100));
//                yValue2.add((float) (Math.random() * 100));
//        }
//        yValues.add(yValue1);
//        //颜色集合
//        List<Integer> colours = new ArrayList<>();
//        colours.add(Color.GREEN);
//        colours.add(Color.BLUE);
//
//
//        //创建多条折线的图表
//       // barChartManager1.showBarChart(xValues, yValues.get(0), names.get(1), colours.get(3));
//        //barChartManager1.showBarChart(xValues, yValues, names, colours);
//        barChartManager1.setTwoBarChart(barChart,xValues,yValue1,yValue2,"上月","本月");
       // barChartManager1.setXAxis(12f, 1f, 12);
        niceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view;
                    type = 1;
                    month = Integer.parseInt(textView.getText().toString().substring(textView.getText().toString().length()-2,textView.getText().toString().length()));
                    loadData(textView.getText().toString());
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        niceSpinner_week.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view;
                type = 2;
                Calendar calendar=Calendar.getInstance();  //获取当前时间，
                String year=calendar.get(Calendar.YEAR)+"";
                loadData(textView.getText().toString().substring(0,10));
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        loadData(TimerUtil.GetlistMonthAndDayDate().get(0));
    }

    @Override
    protected void formatData() {

        tv_monthly.setTextColor(getResources().getColor(R.color.homepage_titlefont));
        niceSpinner.attachDataSource(TimerUtil.GetlistMonthAndDayDate());
        String str  = TimerUtil.GetlistMonthAndDayDate().get(niceSpinner.getSelectedIndex());
        month = Integer.parseInt(str.substring(str.length()-2,str.length()));
        niceSpinner_week.setVisibility(View.GONE);

    }
    private void loadData(String date){
        Map<String,String> map = new HashMap<>();
        map.put("type",type+"");
        map.put("date",date);
        post("personal/studyReport",map, StudyReportDetailBean.class,false);
    }
    @Override
    protected void getBundle() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_monthly:
                tv_monthly.setTextColor(getResources().getColor(R.color.homepage_titlefont));
                tv_weekly.setTextColor(getResources().getColor(R.color.font_color));
                niceSpinner.setVisibility(View.VISIBLE);
                niceSpinner_week.setVisibility(View.GONE);
                break;
            case R.id.tv_weekly:
                tv_monthly.setTextColor(getResources().getColor(R.color.font_color));
                tv_weekly.setTextColor(getResources().getColor(R.color.homepage_titlefont));
                niceSpinner.setVisibility(View.GONE);
                niceSpinner_week.setVisibility(View.VISIBLE);
                niceSpinner_week.attachDataSource(initWeekData());
                break;
        }
    }
}
